package com.itheima.reggic.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggic.common.R;
import com.itheima.reggic.dto.DishDto;
import com.itheima.reggic.pojo.Category;
import com.itheima.reggic.pojo.Dish;
import com.itheima.reggic.pojo.DishFlavor;
import com.itheima.reggic.service.CategoryService;
import com.itheima.reggic.service.DishFlavorService;
import com.itheima.reggic.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 菜品管理
 */
@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private CategoryService categoryService;


    @GetMapping("/page")
    public R<Page> page(Integer page, Integer pageSize, String name) {
        Page<Dish> pageObj = new Page<>(page, pageSize);
        Page<DishDto> pageDto = new Page<>(page, pageSize);

        // 查询分类字段
        List<Category> list = categoryService.list();
        // 由于分类菜单的name是唯一的，所以可以查询出分类数据，然后将其组合为key-value形式
        // 可以减少数据库的请求次数
        HashMap<Long, String> categoryMap = new HashMap<>();
        list.forEach(category -> {
            categoryMap.put(category.getId(), category.getName());
        });

        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotEmpty(name), Dish::getName, name);

        queryWrapper.orderByDesc(Dish::getSort);

        dishService.page(pageObj, queryWrapper);
        // 被拷贝的对象，需要拷贝的对象，忽略的属性(字段)
        BeanUtils.copyProperties(pageObj, pageDto, "records");

        // 定义最后结果集,由于pageDto.getRecords() 获取的集合是一个不可变的列表或只读列表，因此无法执行添加操作。
        // 所以转为ArrayList
        ArrayList<DishDto> dishDtoList = new ArrayList<>(pageDto.getRecords());

        // 遍历每一个菜品，查询他们的CategoryName，并赋值给DishDto
        pageObj.getRecords().forEach(dish -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dish, dishDto);
            dishDto.setCategoryName(categoryMap.get(dish.getCategoryId()));
            dishDtoList.add(dishDto);
        });
        // 将最后的结果集返回给pageDto
        pageDto.setRecords(dishDtoList);
        return R.success(pageDto);

    }

    @PostMapping
    public R<String> add(@RequestBody DishDto dish) {
        log.info("添加新菜品:{}", dish);
        dishService.addWithFlavor(dish);

        return R.success("添加成功!");
    }

    @GetMapping("/{id}")
    public R<DishDto> getById(@PathVariable Long id) {

        DishDto dishDto = dishService.getByIdWithFlavor(id);

        return R.success(dishDto);
    }


    @PostMapping("/status/{status}")
    public R<String> changeStatus(@PathVariable Integer status, String ids) {
        log.info("操作菜品状态:{},id:{}", status, ids);
        if (status == null && ids == null)
            return R.error("操作失败!");
        Dish dish = new Dish();
        dish.setId(Long.parseLong(ids));
        dish.setStatus(status);
        dishService.updateById(dish);
        return R.success("操作成功 !");
    }

    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto) {
        boolean flag = dishService.updateByIdWithFlaover(dishDto);

        return R.success("更新成功!");
    }

    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish) {

        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        // 查询结果
        queryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        // 对起售的商品进行查询
        queryWrapper.eq(Dish::getStatus, 1);
        // 对结果进行排序
        queryWrapper.orderByAsc(Dish::getSort)
                .orderByDesc(Dish::getUpdateTime);
        List<Dish> dishList = dishService.list(queryWrapper);

        List<DishDto> dishDtos = new ArrayList<>();

        for (Dish t : dishList
        ) {
            DishDto dishDto = dishService.getByIdWithFlavor(t.getId());
            dishDtos.add(dishDto);
        }


        return R.success(dishDtos);
    }
}
